<?php
require './pdoconfig.php';

// 连接
try {
    $pdo = new PDO(DSN, USER, PASS);
    // 设置字符集
    $pdo->query('set names utf8');

    // 设置PDO连接属性
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    // 关闭自动提交
    $pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, 0);
    // 开启事务操作
    $pdo->beginTransaction();

} catch (PDOException $e) {
    echo $e->getMessage();
    exit;
}

// 操作
try {
    // 批量插入
    $data = [
        ['无敌', '1', '21','17807616147',MD5(123456)],
        ['嘎达', '0', '43','17807616143',MD5(123456)],
        ['妮妮', '1', '92','17807616149',MD5(123456)]
    ];
    // var_dump($data);die;
    $sql = "INSERT INTO user (nickname,sex,age,tel,pwd) VALUES (?, ?, ?, ?, ?)";
    $stmt = $pdo->prepare($sql);

    // 遍历执行
    $count = 0;
    $ids = [];
    foreach ($data as $v) {
        $stmt->execute($v);
        $count += $stmt->rowCount();
        $ids[] = $pdo->lastInsertId();
    }


    // 判断
    echo "共插入{$count}条数据";

    $pdo->commit();
}catch (PDOException $e) {
    $pdo->rollback();
    echo $e->getMessage();
    exit;
}